package com.pengtu.gsj.service.impl.check.lwfw;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.pengtu.gsj.entity.app.Attachment;
import com.pengtu.gsj.entity.check.CheckTable;
import com.pengtu.gsj.service.check.CheckTableService;
import com.pengtu.gsj.service.lwfw.EmergBaseService;
import com.pengtu.gsj.service.system.SystemManageService;
import com.pengtu.gsj.utils.MathsUtils;

@Service
@Transactional
public class EmergBaseServiceImpl implements EmergBaseService{

	@Autowired
	public SystemManageService systemManageService;
	@Autowired
	public CheckTableService checkTableService;
	
	@Override
	public Map<String, Object> getEmergBases(String startTime, String endTime, CheckTable checkTable, String tag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<Attachment> list = new ArrayList<Attachment>();
		List<Attachment> resultAtts = new ArrayList<Attachment>();
		
		JSONObject jsonObject = JSONObject.parseObject(checkTable.getRetrieval());
		double yearFull = Double.parseDouble((String)jsonObject.get("yearFull"));
		double yearPart = Double.parseDouble((String)jsonObject.get("yearPart"));
		double tableFull = MathsUtils.formatDouble(yearFull + yearPart, 1);
		double percentage = 0; //完善率
		double total = 0; //计算总分
		
		//根据时间、标签查询是否有附件
		list = systemManageService.getCheckAttachments(startTime, endTime, tag);
		//根据是否有相关文件，
		resultAtts = systemManageService.getAllCheckAttachments("bzjd_xgwj");
		if (resultAtts.size() == 0) {
			yearFull = 0;
		}
		total = MathsUtils.formatDouble(yearFull + yearPart, 1);
		percentage = MathsUtils.divDouble(total*100, tableFull, 2);
		
		//只有当系统完善度和检查得分不相等的情况下才更新数据  避免每次搜索都更新数据
		checkTableService.updateCheckTable(checkTable, percentage, total, tableFull, true);
		map.put("att", list);
		map.put("resultAtts", resultAtts);
		map.put("scoreOne", MathsUtils.formatDouble(yearFull, 1));
		map.put("scoreTwo", MathsUtils.formatDouble(yearPart, 1));
		map.put("percent", percentage);
		map.put("score", checkTable.getTestFull());
		map.put("checkTable", checkTable);
		return map;
	}
}
